package com.ms.action.basic;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eddy.util.AjaxOut;
import com.eddy.util.EntityReflect;
import com.eddy.util.ExtLimit;
import com.ms.dao.entity.basic.UserEty;
import com.ms.dao.mapper.basic.UserDao;

@Controller
@RequestMapping("/basic/UserAction/")
public class UserAction {
	private static final long serialVersionUID = -4287242141514499750L;

	@Autowired
	private UserDao userDao;
	
	@RequestMapping("search.action")
	public void search(HttpServletRequest request, HttpServletResponse response) {
		try {
			UserEty userEty = (UserEty) EntityReflect.createObjectFromRequest(request, UserEty.class);
			ExtLimit limit = (ExtLimit) EntityReflect.createObjectFromRequest(request, ExtLimit.class);
			userEty.setExtLimit(limit);
			int count = userDao.selectLimitCount(userEty);
			List list = userDao.selectByLimit(userEty);
			AjaxOut.responseJSonGrid(response, list, count, new SimpleDateFormat("yyyy-MM-dd"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("save.action")
	public void save(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("success", true);
		try {
			UserEty userEty = (UserEty) EntityReflect.createObjectFromRequest(request, UserEty.class);
			if(userEty.getId() == null) {
				userDao.insert(userEty);
			}
			else {
				userDao.updateById(userEty);
			}
			
			obj.put("result", "success");
		} catch (Exception e) {
			e.printStackTrace();
		}
		AjaxOut.responseText(response, obj.toString());
	}

	@RequestMapping("delete.action")
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("success", true);
		try {
			String id = request.getParameter("id");
			userDao.deleteById(Integer.parseInt(id));
			obj.put("result", "success");
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("result", "error");
			obj.put("info", e.getMessage());
		}
		AjaxOut.responseText(response, obj.toString());
	}

	@RequestMapping("getDetailInfo.action")
	public void getDetailInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("success", true);
		try {
			String id = request.getParameter("id");
			UserEty userEty = userDao.selectByUserId(Integer.parseInt(id));
			obj.put("data", userEty);
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("result", "error");
			obj.put("info", e.getMessage());
		}
		AjaxOut.responseText(response, obj.toString());
	}
}
